//
//  QRCodeCardViewController.swift
//  mySwift
//
//  Created by 高赛 on 2016/9/28.
//  Copyright © 2016年 高赛. All rights reserved.
//

import UIKit

class QRCodeCardViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "我的名片"
        
        view.addSubview(iconView)
        
        let _ = iconView.xmg_AlignInner(type: XMG_AlignType.Center, referView: view, size: CGSize(width: 200, height: 200))
        
        let grcodeImage = creatQRCodeImage()
        
        iconView.image = grcodeImage
        
    }
    
    private func creatQRCodeImage() -> UIImage {
        
        // 创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        // 还原滤镜的默认属性
        filter?.setDefaults()
        // 设置需要生成的二维码的数据
        filter?.setValue("LDeath".data(using: String.Encoding.utf8), forKey: "inputMessage")
        // 从滤镜中取出生成好的图片
        let ciImage = filter?.outputImage
        // 创建一个头像
        // 合成图片(将二维码和头像进行合成)
        // 返回生成号的二维码
        let img = createNonInterpolatedUIImageFormCIImage(image: ciImage!, size: 300)
        return img
    }
    /**
     根据CIImage生成指定大小的高清UIImage
     
     :param: image 指定CIImage
     :param: size    指定大小
     :returns: 生成好的图片
     */
    private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
        
//        let extent: CGRect = 
        let extent: CGRect = image.extent.integral
        let scale: CGFloat = min(size/extent.width, size/extent.height)
        
        // 1.创建bitmap;
        let width = extent.width * scale
        let height = extent.height * scale
        
        let cs: CGColorSpace = CGColorSpaceCreateDeviceGray()
        
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: extent)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        
        bitmapRef.scaleBy(x: scale, y: scale)
        
        bitmapRef.draw(bitmapImage, in: extent)
        
        // 2.保存bitmap到图片
        let scaledImage: CGImage = bitmapRef.makeImage()!
        
        return UIImage(cgImage: scaledImage)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // mark -懒加载
    private lazy var iconView: UIImageView = UIImageView()

}
